package catalina.container;

import java.io.*;

public class ContextClassLoader extends ClassLoader {
    //指定路径
    private String path ;
    public ContextClassLoader(String classPath){
        path=classPath;
    }
    /**
     * 重写findClass方法
     * @param name 是我们这个类的全路径
     * @return
     */
    @Override
    protected Class<?> findClass(String name) {
        Class classObject = null;
        String filePath = path+name.replaceAll("\\.", "\\\\")+".class";
        // 获取该class文件字节码数组
        byte[] classData = getData(filePath);
        if (classData != null) {
            // 将class的字节码数组转换成Class类的实例
            classObject = defineClass(name, classData, 0, classData.length);
        }
        return classObject;
    }

    /**
     * 将class文件转化为字节码数组
     * @return
     */
    private byte[] getData(String filePath) {
        File file = new File(filePath);
        if (file.exists()){
            FileInputStream in = null;
            ByteArrayOutputStream out = null;
            try {
                in = new FileInputStream(file);
                out = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int size = 0;
                while ((size = in.read(buffer)) != -1) {
                    out.write(buffer, 0, size);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return out.toByteArray();
        }else{
            return null;
        }
    }
}
